package com.leaf.collegeidleapp.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
//import androidx.annotation.Nullable;
import androidx.annotation.Nullable;
import com.leaf.collegeidleapp.bean.Star;

import java.util.ArrayList;
import java.util.List;

public class StarDBHelper extends SQLiteOpenHelper {

    //定义数据库表名
    public static final String DB_NAME = "tb_star";
    /** 创建收藏信息表 **/
    private static final String CREATE_STAR_DB = "create table tb_star (" +
            "id integer primary key autoincrement," +
            "stuId text," +
            "phone text )";


    public StarDBHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_STAR_DB);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /**
     * 添加我的关注
     * @param star 收藏对象
     */
    public void addMyStar(Star star) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("stuId",star.getStuId());
        values.put("phone",star.getPhone());
        db.insert(DB_NAME,null,values);
        values.clear();
    }

    /**
     * 通过学号获取我的关注
     */
    public List<Star> readMyStars(String stuId) {
        List<Star> stars = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from tb_star where stuId = ?", null);
        if(cursor.moveToFirst()) {
            do {
                String phone = cursor.getString(cursor.getColumnIndex("phone"));
                Star star = new Star();
                star.setPhone(phone);
                stars.add(star);
            }while (cursor.moveToNext());
        }
        cursor.close();
        return stars;
    }

    /**
     * 查找全部关注
     */
    public List<Star> readAllStars() {
        List<Star> stars = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from tb_star", null);
        if(cursor.moveToFirst()) {
            do {
                String phone = cursor.getString(cursor.getColumnIndex("phone"));
                Star star = new Star();
                star.setPhone(phone);
                stars.add(star);
            }while (cursor.moveToNext());
        }
        cursor.close();
        return stars;
    }

    /**
     * 删除关注的商品项
     */
    public void deleteMyStar(String phone) {
        SQLiteDatabase db = this.getWritableDatabase();
        if(db.isOpen()) {
            db.delete(DB_NAME,"phone=?",new String[]{phone});
            db.close();
        }
    }
}
